package com.tifa.myssm.baseDao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class ConnUtil {
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    public static String URL;
    public static String DRIVER;
    public static String USER;
    public static String PWD;

    static {
        InputStream is = ConnUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        var properties = new Properties();
        try {
            properties.load(is);
            DRIVER = properties.getProperty("jdbc.driver");
            URL = properties.getProperty("jdbc.url");
            USER = properties.getProperty("jdbc.user");
            PWD = properties.getProperty("jdbc.password");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static Connection creatConn() {
        try {
            Class.forName(DRIVER);
            return DriverManager.getConnection(URL, USER, PWD);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获得 conn 链接
     *
     * @return
     */
    public static Connection getConn() {
        Connection connection = threadLocal.get();
        if (connection == null) {
            connection = creatConn();
            threadLocal.set(connection);
        }
        return threadLocal.get();
    }

    /**
     * 关闭链接
     */
    public static void close() {
        Connection connection = threadLocal.get();
        if (connection == null) {
            return;
        }
        try {
            if (!connection.isClosed()) {
                connection.close();
                threadLocal.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}